﻿var sqlHelper = require('./../common/SqlHelper');
var users = require('./../common/UserCache');
var authorize = require('./../handler/authorize');

var me = module.exports = {
    handlerName: 'message',

    returnData: function (data, obj, callBack) {
        //向客服端发送消息
        if (callBack) {
            callBack(obj);
        }
        //response有值,说明是post请求,需要返回数据
        if (data.res) {
            data.res.send(obj.code, JSON.stringify(obj));
        }
    },

    //保存消息
    sendMessage: function (data, callBack) {
        var obj = {
            code: 200,
            success: false,
            detail: ''
        };

        try {
            var params = {
                appId: data.appId,
                appName: data.appName,
                userId: data.userId,
                userName: data.userName,
                content: data.content,
                link: data.link,
                messageType: data.messageType,
                userImagePath: data.userImagePath
            }

            //判断用户是否在线
            if (data.targetJson) {
                if (typeof data.targetJson == 'string') {
                    data.targetJson = JSON.parse(data.targetJson);
                }

                for (var i in data.targetJson) {
                    var _target = data.targetJson[i];

                    var userSocket = users.userList[_target.userId];
                    if (userSocket) {
                        _target.pushed = 1;
                    } else {
                        _target.pushed = 0;
                    }
                }
                params.targetJson = JSON.stringify(data.targetJson);
            }

            sqlHelper.exec('dbo.pSendMessage', params, function (err, result) {
                if (!err) {
                    obj.success = true;
                    obj.detail = '发送成功';
                    
                    var record = result.recordset;

                    for (var i in data.targetJson) {
                        var _target = data.targetJson[i];

                        var userSocket = users.userList[_target.userId];
                        //用户在线 则推送消息
                        if (userSocket) {
                            //筛选当前用户信息
                            var arrry =[];
                            for(var i=0; i<record.length; i++){
                               if(record[i].TargetUserId==_target.userId)
                                arrry.push(record[i]);
                            }
                            obj.data={
                                totalCount: arrry.length,
                                rows: arrry
                            }
                            //向客服端发送消息
                            userSocket.socket.emit('receiveMessage', obj, callBack);
                        }
                    }

                    obj.data = {
                        totalCount: record.length,
                        rows: record
                    };
                } else {
                    obj.code = 500
                    obj.detail = err.message
                }
                delete obj.targetJson;
                me.returnData(data, obj, callBack);
            });
        } catch (e) {
            Console.log(e);
        }
    },

    //查询消息
    queryMessage: function (data, callBack) {
        var obj = {
            code: 200,
            success: false,
            detail: ''
        };

        try {
            var params = {
                appId: data.appId,
                userId: data.userId,
                readStatus: data.readStatus,
                deleted: data.deleted,
                pushed: data.pushed,
                messageType:data.messageType,
                start:data.start,
                limit:data.limit
            }

            sqlHelper.exec('dbo.pQueryMessageList', params, function (err, result) {
                if (!err) {
                    var json = '';
                    var record = result.recordset;
                    obj.success = true;

                    if (record.length > 0) {
                        obj.detail = '查询列表成功';
                    }
                    else {
                        obj.detail = '查无数据';
                    }

                    obj.data = {
                        totalCount: result.returnValue,
                        rows: record
                    }
                } else {
                    obj.code = 500
                    obj.detail = err.message
                }
                me.returnData(data, obj, callBack);
            });
        } catch (e) {
            Console.log(e);
        }
    },

    //更新信息状态
    updateMessageReadStatus: function (data, callBack) {
        var obj = {
            code: 200,
            success: false,
            detail: ''
        };

        try {
            var params = {
                id: data.id
            }

            sqlHelper.exec('dbo.pUpdateMessageReadStatus', params, function (err, result) {
                if (!err) {
                    obj.success = true;
                    obj.detail = '修改成功';
                } else {
                    obj.code = 500
                    obj.detail = err.message
                }

                me.returnData(data, obj, callBack);
            });
        } catch (e) {
            Console.log(e);
        }
    },

    //删除信息(软删除)
    deleteMessage: function (data, callBack) {
        var obj = {
            code: 200,
            success: false,
            detail: ''
        };

        try {
            var params = {
                id: data.id
            }

            sqlHelper.exec('dbo.pDeleteMessage', params, function (err, result) {
                if (!err) {
                    obj.success = true;
                    obj.detail = '删除成功';
                } else {
                    obj.code = 500
                    obj.detail = err.message
                }

                me.returnData(data, obj, callBack);
            });
        } catch (e) {
            Console.log(e);
        }
    },
    //保存key的接口
    saveAuthorization: function (data, callBack) {
        var obj = {
            code: 200,
            success: false,
            detail: ''
        };

        try {
            var params = {
                appId: data.appId,
                key: data.key,
                tag: data.tag ? data.tag : 0
            }

            sqlHelper.exec('dbo.pSaveAuthorization', params, function (err, result) {
                if (!err) {
                    obj.success = true;
                    obj.detail = '保存成功';
                } else {
                    obj.code = 500
                    obj.detail = err.message
                }

                me.returnData(data, obj, callBack);
            });
        } catch (e) {
            Console.log(e);
        }
    },
    //保存账户的接口
    saveAccount: function (data, callBack) {
        var obj = {
            code: 200,
            success: false,
            detail: ''
        };

        try {
            var params = {
                account: data.account,
                password: data.password,
                name:data.name,
                tag: data.tag ? data.tag : 0
            }

            sqlHelper.exec('dbo.pSaveAccount', params, function (err, result) {
                if (!err) {
                    obj.success = true;
                    obj.detail = '保存成功';
                } else {
                    obj.code = 500
                    obj.detail = err.message
                }

                me.returnData(data, obj, callBack);
            });
        } catch (e) {
            Console.log(e);
        }
    }
}